package com.example.demo.Service.Impl;

import com.example.demo.Common.OException;
import com.example.demo.Common.ServiceResultEnum;
import com.example.demo.Dao.AdminMapper;
import com.example.demo.Dao.CustomerMapper;
import com.example.demo.Dao.UserTokenMapper;
import com.example.demo.Entity.Admin;
import com.example.demo.Entity.Customer;
import com.example.demo.Entity.UserToken;
import com.example.demo.Param.CustomerUpdateParam;
import com.example.demo.Param.UserInsertParam;
import com.example.demo.Param.UserUpdateParam;
import com.example.demo.Service.UserService;
import com.example.demo.Util.MD5Util;
import com.example.demo.Util.NumberUtil;
import com.example.demo.Util.SystemUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserTokenMapper userTokenMapper;



    @Override
    public String registerC(String userName, String telphone, String password) {
        if (customerMapper.selectByTelphone(telphone) != null) {
            return ServiceResultEnum.SAME_TELPHONE_EXIST.getResult();
        }
        Customer registerUser = new Customer();
        registerUser.setCustomername(userName);
        registerUser.setCustomertel(telphone);
        String passwordMD5 = MD5Util.MD5Encode(password, "UTF-8");
        registerUser.setCustomerpwd(passwordMD5);
        if (customerMapper.insertSelective(registerUser) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public String registerA(String userName, String telphone, String password) {
        return null;
    }

    @Override
    public String loginC(String telphone, String passwordMD5) {
        Customer customer = customerMapper.selectByTelphoneAndPasswd(telphone, passwordMD5);
        if (customer != null) {
            //登录后即执行修改token的操作
            String token = getNewToken(System.currentTimeMillis() + "", customer.getId());
            UserToken userToken = userTokenMapper.selectByPrimaryKey(customer.getId());
            //当前时间
            Date now = new Date();
            //过期时间
            Date expireTime = new Date(now.getTime() + 2 * 24 * 3600 * 1000);//过期时间 48 小时
            if (userToken == null) {
                userToken = new UserToken();
                userToken.setId(customer.getId());
                userToken.setToken(token);
                userToken.setUpdateTime(now);
                userToken.setExpireTime(expireTime);
                //新增一条token数据
                if (userTokenMapper.insertSelective(userToken) > 0) {
                    //新增成功后返回
                    return token;
                }
            } else {
                userToken.setToken(token);
                userToken.setUpdateTime(now);
                userToken.setExpireTime(expireTime);
                //更新
                if (userTokenMapper.updateByPrimaryKeySelective(userToken) > 0) {
                    //修改成功后返回
                    return token;
                }
            }

        }
        return ServiceResultEnum.LOGIN_ERROR.getResult();
    }

    /*@Override
    public String loginA(String telphone, String passwordMD5) {
        Admin admin = adminMapper.selectByTelphoneAndPasswd(telphone, passwordMD5);
        if (admin != null) {
            //登录后即执行修改token的操作
            String token = getNewToken(System.currentTimeMillis() + "", admin.getId());
            UserToken userToken = userTokenMapper.selectByPrimaryKey(admin.getId());
            //当前时间
            Date now = new Date();
            //过期时间
            Date expireTime = new Date(now.getTime() + 2 * 24 * 3600 * 1000);//过期时间 48 小时
            if (userToken == null) {
                userToken = new UserToken();
                userToken.setId(admin.getId());
                userToken.setToken(token);
                userToken.setUpdateTime(now);
                userToken.setExpireTime(expireTime);
                //新增一条token数据
                if (userTokenMapper.insertSelective(userToken) > 0) {
                    //新增成功后返回
                    return token;
                }
            } else {
                userToken.setToken(token);
                userToken.setUpdateTime(now);
                userToken.setExpireTime(expireTime);
                //更新
                if (userTokenMapper.updateByPrimaryKeySelective(userToken) > 0) {
                    //修改成功后返回
                    return token;
                }
            }

        }
        return ServiceResultEnum.LOGIN_ERROR.getResult();
    }*/

    @Override
    public Admin loginA(String userName, String password) {
        Admin admin = adminMapper.selectByLoginNameAndPasswd(userName, password);
        return admin;
    }

    @Override
    public Boolean updateAdminInfo(UserUpdateParam user, Long userId) {
        Admin admin = adminMapper.selectByPrimaryKey(userId);
        if (admin == null) {
            OException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        //user.setPasswordMd5(mallUser.getPasswordMd5());
        //若密码为空字符，则表明用户不打算修改密码，使用原密码保存
        if (!MD5Util.MD5Encode("", "UTF-8").equals(user.getPasswordMd5())){
            admin.setUserpwd(user.getPasswordMd5());
        }
        if (adminMapper.updateByPrimaryKeySelective(admin) > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean updateCustomerInfo(UserUpdateParam user) {
        Customer customer = customerMapper.selectByLoginName(user.getUserName());
        if (customer == null) {
            OException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        //user.setPasswordMd5(mallUser.getPasswordMd5());
        //若密码为空字符，则表明用户不打算修改密码，使用原密码保存
        if (!MD5Util.MD5Encode("", "UTF-8").equals(user.getPasswordMd5())){
            customer.setCustomerpwd(user.getPasswordMd5());
        }
        if (customerMapper.updateByPrimaryKeySelective(customer) > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean logoutA(Long userId) {
        return userTokenMapper.deleteByPrimaryKey(userId) > 0;
    }

    @Override
    public Boolean logoutC(Long userId) {
        return userTokenMapper.deleteByPrimaryKey(userId) > 0;
    }

    @Override
    public Customer getCDetail(String usertel) {
        return customerMapper.selectByTelphone(usertel);
    }

    @Override
    public List<Customer> getAll() {
        List<Customer> customers = customerMapper.selectAll();
        return customers;
    }

    @Override
    public void deleteCustomer(Long id) {
        customerMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void updateCustomer(CustomerUpdateParam customerUpdateParam) {
        Customer customer = new Customer();
        customer.setId(customerUpdateParam.getId());
        customer.setCustomername(customerUpdateParam.getCustomername());
        customer.setCustomertel(customerUpdateParam.getCustomertel());
        customer.setCustomeraddress(customerUpdateParam.getCustomeraddress());
        Customer usedCustomer = customerMapper.selectByPrimaryKey(customerUpdateParam.getId());
        customer.setCustomerpwd(usedCustomer.getCustomerpwd());
        customerMapper.updateByPrimaryKey(customer);
    }

    @Override
    public Customer findCustomerById(Long id) {
        return customerMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Customer> searchCustomer(String customername) {
        List<Customer> customers = customerMapper.selectByCustomerName(customername);
        return customers;
    }

    @Override
    public Customer createOne(UserInsertParam userInsertParam) {
        Customer customer = new Customer();
        customer.setCustomername(userInsertParam.getCustomername());
        customer.setCustomertel(userInsertParam.getCustomertel());
        customer.setCustomerpwd("12345678");
        customer.setCustomeraddress(userInsertParam.getCustomeraddress());
        customerMapper.insert(customer);
        return customer;
    }

    /**
     * 获取token值
     *
     * @param timeStr
     * @param userId
     * @return
     */
    private String getNewToken(String timeStr, Long userId) {
        String src = timeStr + userId + NumberUtil.genRandomNum(4);
        System.out.println(timeStr);
        System.out.println(NumberUtil.genRandomNum(4));
        return SystemUtil.genToken(src);
    }
}
